﻿using System;

namespace Script.Net
{
    public class TcpTransData
    {
        public byte[] Buffer = new byte[Const.TcpBufferSize];
        public byte[] Data;
        public int CurrentProgress;
        public int TotalProgress;
        public bool HeaderReadComplete;
        public bool IsComplete
        {
            get { return CurrentProgress >= TotalProgress; }
        }

        public bool Read(int readLen)
        {
            if (!HeaderReadComplete)
            {
                byte[] lengthByte = new byte[Const.LengthInfoByteCount];
                Array.Copy(Buffer, lengthByte, Const.LengthInfoByteCount);
                TotalProgress = NetUtil.Byte2Int(lengthByte);
                HeaderReadComplete = true;
                Data = new byte[TotalProgress];
                CurrentProgress = 0;
                int currentLeftBuffer = readLen - Const.LengthInfoByteCount;
                if (currentLeftBuffer > 0)
                {
                    Array.ConstrainedCopy(Buffer, Const.LengthInfoByteCount, Data, 0, currentLeftBuffer);
                    CurrentProgress += currentLeftBuffer;
                }
            }
            else
            {
                Array.ConstrainedCopy(Buffer, 0, Data, CurrentProgress, readLen);
                CurrentProgress += readLen;
            }

            return Data != null && CurrentProgress == TotalProgress;
        }

        public void Reset()
        {
            Data = null;
            CurrentProgress = 0;
            TotalProgress = 0;
            HeaderReadComplete = false;

        }
    }
}